﻿using Microsoft.Research.DynamicDataDisplay;
using Microsoft.Research.DynamicDataDisplay.DataSources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TrailMapManager.Common.Track;
using TrailMapManager.Modules.Track.Logic;

namespace TrailMapManager.Modules.Track.View
{
    /// <summary>
    /// Interaction logic for TrackMainView.xaml
    /// </summary>
    public partial class TrackMainView : UserControl
    {
        public TrackMainView()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded_1(object sender, RoutedEventArgs e)
        {
            (this.DataContext as TrackMainViewLogic).Update += TrackMainView_Update;
            cursorGraph.XTextMapping = new Func<double, string>(
                value =>
                {
                    var timePosition = dateTimeAxis.ConvertFromDouble(value);
                    (this.DataContext as TrackMainViewLogic).CursorPosition = timePosition;
                    return timePosition.ToLongTimeString();
                });
        }

        void TrackMainView_Update()
        {
            foreach (var item in chart.Children)
            {
                if (item is LineGraph)
                {
                    chart.Children.Remove(item);
                    break;
                }
            }
            chart.FitToView();
            Plotter2DExtensions.AddLineGraph(chart, CreateDataSourceSpeed((this.DataContext as TrackMainViewLogic).ChartData), Colors.Black, 1, "Speed");
            Plotter2DExtensions.AddLineGraph(chart, CreateDataSourceAltitude((this.DataContext as TrackMainViewLogic).ChartData), Colors.Green, 1, "Altitude");
        }

        private EnumerableDataSource<TrailTrackPoint> CreateDataSourceSpeed(List<TrailTrackPoint> rates)
        {
            EnumerableDataSource<TrailTrackPoint> ds = new EnumerableDataSource<TrailTrackPoint>(rates);
            ds.SetXMapping(ci => dateTimeAxis.ConvertToDouble(ci.TimeStamp));
            ds.SetYMapping(ci => ci.Speed);
            return ds;
        }

        private EnumerableDataSource<TrailTrackPoint> CreateDataSourceAltitude(List<TrailTrackPoint> rates)
        {
            EnumerableDataSource<TrailTrackPoint> ds = new EnumerableDataSource<TrailTrackPoint>(rates);
            ds.SetXMapping(ci => dateTimeAxis.ConvertToDouble(ci.TimeStamp));
            ds.SetYMapping(ci => ci.Altitude);
            
            return ds;
        }
        
    }
}
